package com.lgx.common.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.basic.dao.GeneralJdbcDao;
import com.lgx.common.dao.IDictionaryDao;
import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.tree.TreeUtils;

@Component
public class DictionaryDao extends GeneralDao implements IDictionaryDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private GeneralJdbcDao baseDao;
	
	public GeneralJdbcDao getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(GeneralJdbcDao baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	@Transactional
	public Dictionary createDictionary(Dictionary dict) throws DataException {
		this.getHibernateTemplate().save(dict);
		log.info("[创建字典]:"+dict.getId());
		return dict;
	}

	@Override
	@Transactional
	public Dictionary updateDictionary(Dictionary dict) throws DataException {
		this.getHibernateTemplate().update(dict);
		log.info("[更新字典]:"+dict.getId());
		return dict;
	}

	@Override
	@Transactional
	public void deleteDictionary(Dictionary dict) throws DataException {
		log.info("[删除字典]:"+dict.getId());
		this.getHibernateTemplate().delete(dict);
	}

	@Override
	public void deleteDictionary(String id) throws DataException {
		deleteDictionary(this.findDictionaryById(id));
	}

	@Override
	public Dictionary findDictionaryById(String id) {
		return this.getHibernateTemplate().get(Dictionary.class, Long.parseLong(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionaryList() {
		String sql = "select d.* from ts_dictionary d  order by d.layerorder asc";
		List<Dictionary> ds = (List<Dictionary>) this.baseDao.queryJdbcForList(sql, Dictionary.class);
		return (List<Dictionary>) TreeUtils.addChildren(ds, null, null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionaryList(String kind) {
		String hql = "from Dictionary d where d.kind = '"+kind+"' and d.leaf = true order by d.code asc";
		return this.getHibernateTemplate().find(hql);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Dictionary> findDictionaryKind() {
		String hql = "from Dictionary d where d.leaf = false and d.parent=1";
		return this.getHibernateTemplate().find(hql);
	}

}
